package com.mamingchao.concurrent.threads_communication3;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A在唤醒操作之后，并不释放锁。这种方法跟 Object 的 wait() 和 notify() 一样。
 *
 * Created by mamingchao on 2020/9/19.
 */
public class UseReentrantLockCondition {

    static ReentrantLock lock = new ReentrantLock();

    static List<Integer> lists = new ArrayList<>();

    public static void main(String[] args) {

        Condition condition = lock.newCondition();

        Thread b = new Thread( ()->{
            lock.lock();

            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程B收到通知，开始执行自己的业务...");

//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            lock.unlock();
        });

        Thread a = new Thread(() -> {

            lock.lock();

            for (int i = 0; i < 10; i++) {
                lists.add(i);
                System.out.println(i);
                if (i == 5){
                    condition.signal();
                }
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

            lock.unlock();

        });


        b.start();
        a.start();
    }
}
